package org.homeworkteam.controller;

import org.homeworkteam.bean.Chat;
import org.homeworkteam.webSocket.SimpleWebSocketHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;

@CrossOrigin
@RestController
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    private SimpleWebSocketHandler webSocketHandler;

    @GetMapping("/send")
    public String sendMessage(String from, String to, String content) {
        if (from == null || to == null || content == null || from.isEmpty() || to.isEmpty() || content.isEmpty()) {
            return "Error: 参数不完整，请提供 from, to 和 content。";
        }

        // 构建消息

        Chat chat = new Chat();
        chat.setUserId(from); // 设置发送者
        chat.setAdminId(to); // 设置接收者
        chat.setChatContent(content); // 设置聊天内容

// 设置时间为当前时间
        chat.setTime(new Timestamp(System.currentTimeMillis()));
        // 构造消息文本
        String message = String.format(
                "{\"from\":\"%s\", \"to\":\"%s\", \"message\":\"%s\", \"time\":\"%s\"}",
                from, to, content, chat.getTime().toString()
        );

        // 推送消息到指定接收者
        System.out.println("Attempting to send message: " + message);
        boolean success = webSocketHandler.sendMessageToUser(to, message);
        if (success) {
            return "Message sent to user " + to + ": " + content;
        } else {
            return "Failed to send message. User " + to + " is not connected.";
        }
    }
}
